<?php
/**
 * Created by PhpStorm.
 * User: aiChenK
 * Date: 2019-01-24
 * Time: 14:29
 */
namespace Services\Msg\Core;

/**
 * Class BaseCreator
 * @package Services\Msg\Core
 *
 * create by ck 20190124
 */
abstract class BaseCreator
{
    //打开方式
    const VIEW_MODAL = 1;
    const VIEW_TAB   = 3;
    const VIEW_PAGE  = 4;

    //重要等级
    const LEVEL_NORMAL    = 1;
    const LEVEL_IMPORTANT = 2;
    const LEVEL_EMERGENCY = 3;

    //关联参数
    protected $module;
    protected $subModule;
    protected $extraId;
    protected $operate;

    //内容参数
    protected $title    = '';
    protected $url      = '';
    protected $viewMode = self::VIEW_MODAL;
    protected $level    = self::LEVEL_NORMAL;

    protected $receiver = [];

    public function __construct(string $module, string $subModule, $extraId = 0)
    {
        if (!$module || !$subModule) {
            throw new \Exception('模块名不能为空');
        }
        $this->module    = $module;
        $this->subModule = $subModule;
        $this->extraId   = $extraId;
    }

    public function setOperate(string $operate)
    {
        $this->operate = $operate;
        return $this;
    }

    public function setReceiver(array $userIds = [])
    {
        $this->receiver = $userIds;
        return $this;
    }

    public function addReceiver($userIds)
    {
        if ($userIds) {
            if (is_numeric($userIds)) {
                $this->receiver[] = $userIds;
            } else {
                $this->receiver = array_merge($this->receiver, $userIds);
            }
        }
        return $this;
    }

    public function setTitle(string $title)
    {
        $this->title = $title;
        return $this;
    }

    public function setUrl(string $url)
    {
        $this->url = $url;
        return $this;
    }

    public function setViewMode($mode = self::VIEW_MODAL)
    {
        $this->viewMode = $mode;
        return $this;
    }

    public function setLevel($level = self::LEVEL_NORMAL)
    {
        $this->level = $level;
        return $this;
    }

    protected function validate()
    {
        $this->receiver = array_values(array_filter($this->receiver));
        if (!$this->title) {
            throw new \Exception('标题不能为空');
        }
        if (!$this->receiver) {
            throw new \Exception('接收者不能为空');
        }

        //判断tab/page打开时url是否存在
        if (in_array($this->viewMode, [self::VIEW_TAB, self::VIEW_PAGE]) && !$this->url) {
            throw new \Exception('选择的打开方式需填写url');
        }
    }
}
